【android】存储数组数据到SharedPreferences

如果要数组数据(如boolean[] 、int[]等)到SharedPreferences时,我们可以先将数组数据组织成json数据存储到SharedPreferences,读取时则对json数据进行解析就ok了。 

例如,我要保存boolean[] 数组数据:

	public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) {
		SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
		JSONArray jsonArray = new JSONArray();
		for (boolean b : booleanArray) {
			jsonArray.put(b);
		}
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(APK_ENABLE_ARRAY,jsonArray.toString());
		editor.commit();
	}


读取数据:

	public static boolean[] getApkEnableArray(Context context,int arrayLength)
	{
		SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
		boolean[] resArray=new boolean[arrayLength]; 
		Arrays.fill(resArray, true);
		try {
		    JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]"));
		    for (int i = 0; i < jsonArray.length(); i++) {
		    	resArray[i] = jsonArray.getBoolean(i);
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
    	        return resArray;
	}

当保存一些复杂的对象数组时,可以用gson来处理json和object的相互转换。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,你可以使用 SharedPreferences 存储一个字符串数组。下面是一个示例: ```java // 获取 SharedPreferences 实例 SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); // 创建一个字符串数组 String[] colors = {"Red", "Green", "Blue"}; // 将字符串数组转换为以逗号分隔的字符串 String colorsString = TextUtils.join(",", colors); // 将字符串数组存储SharedPreferencesSharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("colors", colorsString); editor.apply(); ``` 在上面的代码中,我们首先获取了一个 SharedPreferences 实例,并将其命名为 "my_prefs"。然后,我们创建了一个字符串数组 colors,将其转换为以逗号分隔的字符串 colorsString,并将其存储SharedPreferences 中。在存储时,我们使用了 SharedPreferences.Editor 的 putString() 方法,并将键名设置为 "colors"。 要获取存储的字符串数组,可以使用以下代码: ```java // 获取 SharedPreferences 实例 SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); // 从 SharedPreferences 中获取存储的字符串数组 String colorsString = sharedPreferences.getString("colors", ""); String[] colors = colorsString.split(","); // 打印字符串数组 for (String color : colors) { Log.d("TAG", color); } ``` 在上面的代码中,我们首先获取了一个 SharedPreferences 实例,并将其命名为 "my_prefs"。然后,我们从 SharedPreferences 中获取存储的字符串数组,使用了 SharedPreferences 的 getString() 方法,并将键名设置为 "colors"。获取到字符串数组后,我们使用 String 的 split() 方法将其拆分为一个字符串数组 colors,并打印出每个元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值